package com.ruoyi.project.order.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.constant.WXConstants;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Slf4j
@RequestMapping("wx")
public class WxController extends BaseController {

    @Autowired
    IUserService userService;

    /**
     * 微信网页授权
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("MP_verify_IH7x7WUM9WX1Q6LD.txt")
    public String Wxwysq() {
        return "IH7x7WUM9WX1Q6LD";
    }

    /**
     * 绑定页面
     */

    @RequestMapping("bd")
    public String openidBinding(String code, String state, Model model) {
        String wxResult = HttpUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WXConstants.AppID + "&secret=" + WXConstants.AppSecret + "&code=" + code + "&grant_type=authorization_code");
        if (wxResult.contains("errcode")) {
            model.addAttribute("msg", "获取opeid失败 可能的原因: 公众号管理员未设置ip白名单,请等待设置后重试: " + wxResult);
            return "msg/error";
        }
        model.addAttribute("openId", JSON.parseObject(wxResult).getString("openid"));
        return "order/wxbd";
    }

    @RequestMapping("bindOpenId")
    public String bindOpenId(String account, String openId,Model model) {
        if (StrUtil.hasBlank(account, openId)) {
            model.addAttribute("msg", "某些参数为空了");
            return "msg/error";
        }
        //查用户
        User user = userService.selectUserByLoginName(account);
        if (user == null) {
            //return "<h1>此用户不存在,请重新绑定</h1>";
            model.addAttribute("msg", "此用户不存在,请重新绑定");
            return "msg/error";

        }
        if (user.getOpenId() != null) {
            model.addAttribute("msg", "此用户已绑定过微信到工单系统了");
            return "msg/error";
        }else {
            //绑定微信
            user.setOpenId(openId);
            userService.updateUserInfo(user);
            model.addAttribute("msg", "您成功绑定了微信, 请退出重新登录工单系统");
            return "msg/success";
        }
     }

}
